﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Server
{
    class Program
    {
        static Socket so;
        static TcpListener tl;
        static void Main(string[] args)
        {
            so = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            tl = new TcpListener(IPAddress.Parse("127.0.0.1"),2012);
            try
            {
                tl.Start();
                
                while (true)
                {
                    so = tl.AcceptSocket();
                    byte[] buffer = new byte[1 << 25];      //定义缓冲区32M
                    int length = buffer.Length;
                    int count = 0;
                    if (so.Connected)
                    {
                        string dirPath = @"C:\receive\";
                        byte[] name = new byte[32];
                        so.Receive(name, 32, SocketFlags.None);
                        using (FileStream fs = new FileStream(dirPath + (Encoding.Default.GetString(name)).Trim(), FileMode.Create))
                        {

                            do
                            {
                                count = so.Receive(buffer, 0, length, SocketFlags.None);
                                fs.Write(buffer, 0, count);
                            } while (count > 0);
                        }


                    }
                }
            }
            catch (System.Exception ex)
            {

            }
        }
        static void AcceptConnect()
        {
            while (true)
	        {
	            if (tl.Pending())
	            {
                    using (Socket s = tl.AcceptSocket())
                    {
                        byte[] buffer = new byte[1 << 25];      //定义缓冲区32M
                        int length = buffer.Length;
                        int count = 0;
                        if (so.Connected)
                        {
                            string dirPath = @"C:\receive\";
                            byte[] name = new byte[32];
                            so.Receive(name, 32, SocketFlags.None);
                            using (FileStream fs = new FileStream(dirPath + (Encoding.Default.GetString(name)).Trim(), FileMode.Create))
                            {

                                do
                                {
                                    count = so.Receive(buffer, 0, length, SocketFlags.None);
                                    fs.Write(buffer, 0, count);
                                } while (count > 0);
                            }


                        }
                    }
	            }
	        }
        }
    }
}
